package cn.bon.security.handler;

import cn.bon.common.adapter.JsonSerializerAdapter;
import cn.bon.common.enums.ResultCode;
import cn.bon.common.tool.R;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

import java.io.IOException;

/**
 * @author: dronff
 * @description:
 * @CreateTime: 2023/12/9 11:50
 **/
public class AuthenticationFailureHandlerImpl implements AuthenticationFailureHandler {
    @Resource
    JsonSerializerAdapter jsonSerializerAdapter;
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        // 没有访问权限
        response.setContentType("application/json");
        response.setStatus(200);
        response.setCharacterEncoding("utf-8");
        response.getWriter().print(
                jsonSerializerAdapter.readObjectAsJson(
                        R.fail(ResultCode.USER_CREDENTIALS_ERROR)
                )
        );
    }
}
